package crypt

import (
	"errors"
	"fmt"
	"strings"
	"time"
)

// var salt = "@bkMySql"
var start = 6
var end = 22

type Code struct {
	Salt string
}

func (code Code) Encrypt(orig string) string {
	t := time.Now().Unix()
	tmp := MD5(fmt.Sprintf("%v", t))
	key := MD5(tmp + code.Salt)
	crypted := AesEncrypt(orig, key[start:end])
	ret := fmt.Sprintf("%s.%s", tmp, crypted)
	return Base64Encrypt(ret)

}

func (code Code) Decrypt(crypted string) (ret string, err error) {
	defer func() {
		if r := recover(); r != nil {
			ret = ""
			err = fmt.Errorf("%v", r)
		}
	}()
	crypted, err = Base64Decrypt(crypted)
	if err != nil {
		return
	}

	keys := strings.Split(crypted, ".")
	if len(keys) != 2 {
		err = errors.New("加密的字符串格式不对")
		return
	}
	key := MD5(keys[0] + code.Salt)
	ret = AesDecrypt(keys[1], key[start:end])
	return
}
